package com.example.archive.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.archive.entity.PhysicalArchiveRetrievalRequest;
import com.example.archive.mapper.PhysicalArchiveRetrievalRequestMapper;
import com.example.archive.service.PhysicalArchiveRetrievalRequestService;
import com.example.archive.service.SystemLogService;
import com.example.archive.util.PageParam;
import com.example.archive.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class PhysicalArchiveRetrievalRequestServiceImpl extends ServiceImpl<PhysicalArchiveRetrievalRequestMapper, PhysicalArchiveRetrievalRequest> 
        implements PhysicalArchiveRetrievalRequestService {

    private static final Logger logger = LoggerFactory.getLogger(PhysicalArchiveRetrievalRequestServiceImpl.class);

    @Autowired
    private PhysicalArchiveRetrievalRequestMapper requestMapper;

    @Autowired
    private SystemLogService systemLogService;

    @Override
    public Result<String> submitRequest(PhysicalArchiveRetrievalRequest request) {
        try {
            // 设置申请时间和状态
            request.setRequestTime(new Date());
            request.setApprovalStatus("pending");
            request.setIsRetrieved(false);
            
            // 插入数据库
            int result = requestMapper.insert(request);
            
            if (result > 0) {
                // 记录系统日志
                systemLogService.recordLog(request.getUserId(), "提交纸质档案调取申请", 
                    "申请ID: " + request.getRequestId() + ", 档案ID: " + request.getArchiveId());
                
                logger.info("用户 {} 提交了纸质档案调取申请，申请ID: {}", request.getUserId(), request.getRequestId());
                return Result.success("申请提交成功，等待领导审批");
            } else {
                return Result.fail(500, "申请提交失败");
            }
        } catch (Exception e) {
            logger.error("提交纸质档案调取申请失败", e);
            return Result.fail(500, "申请提交失败：" + e.getMessage());
        }
    }

    @Override
    public Result<IPage<PhysicalArchiveRetrievalRequest>> listRequests(PageParam pageParam, Integer userId, String userRole, String status) {
        try {
            Page<PhysicalArchiveRetrievalRequest> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
            
            // 根据用户角色决定查询范围
            Integer queryUserId = null;
            if ("普通员工".equals(userRole)) {
                // 普通员工只能查看自己的申请
                queryUserId = userId;
            }
            // 企业领导可以查看所有申请，所以queryUserId保持null
            
            IPage<PhysicalArchiveRetrievalRequest> result = requestMapper.selectRequestsWithDetails(
                page, queryUserId, status, pageParam.getSearch());
            
            logger.info("查询纸质档案调取申请列表，用户ID: {}, 结果数量: {}", userId, result.getRecords().size());
            return Result.success(result);
        } catch (Exception e) {
            logger.error("查询纸质档案调取申请列表失败", e);
            return Result.fail(500, "查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> approveRequest(Integer requestId, String status, String notes, Integer approverId) {
        try {
            PhysicalArchiveRetrievalRequest request = requestMapper.selectById(requestId);
            if (request == null) {
                return Result.fail(404, "申请不存在");
            }

            // 更新审批信息
            request.setApprovalStatus(status);
            request.setApproverId(approverId);
            request.setApprovalTime(new Date());
            request.setNotes(notes);
            
            // 如果批准，生成调取码
            if ("approved".equals(status)) {
                String retrievalCode = generateRetrievalCode();
                request.setRetrievalCode(retrievalCode);
            }

            int result = requestMapper.updateById(request);
            
            if (result > 0) {
                // 记录系统日志
                String action = "approved".equals(status) ? "批准纸质档案调取申请" : "拒绝纸质档案调取申请";
                systemLogService.recordLog(approverId, action, 
                    "申请ID: " + requestId + ", 调取码: " + request.getRetrievalCode());
                
                String message = "approved".equals(status) ? 
                    "申请已批准，调取码：" + request.getRetrievalCode() : "申请已拒绝";
                return Result.success(message);
            } else {
                return Result.fail(500, "审批失败");
            }
        } catch (Exception e) {
            logger.error("审批纸质档案调取申请失败", e);
            return Result.fail(500, "审批失败：" + e.getMessage());
        }
    }

    @Override
    public Result<PhysicalArchiveRetrievalRequest> getRequestDetail(Integer requestId) {
        try {
            Page<PhysicalArchiveRetrievalRequest> page = new Page<>(1, 1000);
            IPage<PhysicalArchiveRetrievalRequest> result = requestMapper.selectRequestsWithDetails(page, null, null, null);
            
            PhysicalArchiveRetrievalRequest request = result.getRecords().stream()
                .filter(r -> r.getRequestId().equals(requestId))
                .findFirst()
                .orElse(null);
            
            if (request != null) {
                return Result.success(request);
            } else {
                return Result.fail(404, "申请不存在");
            }
        } catch (Exception e) {
            logger.error("获取申请详情失败", e);
            return Result.fail(500, "获取详情失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> confirmRetrieval(Integer requestId) {
        try {
            PhysicalArchiveRetrievalRequest request = requestMapper.selectById(requestId);
            if (request == null) {
                return Result.fail(404, "申请不存在");
            }

            if (!"approved".equals(request.getApprovalStatus())) {
                return Result.fail(400, "申请未批准，无法调取");
            }

            if (request.getIsRetrieved()) {
                return Result.fail(400, "档案已调取");
            }

            // 更新调取状态
            request.setIsRetrieved(true);
            request.setActualRetrievalTime(new Date());

            int result = requestMapper.updateById(request);
            
            if (result > 0) {
                // 记录系统日志
                systemLogService.recordLog(request.getUserId(), "确认纸质档案调取", 
                    "申请ID: " + requestId + ", 调取时间: " + new Date());
                
                return Result.success("档案调取确认成功");
            } else {
                return Result.fail(500, "确认失败");
            }
        } catch (Exception e) {
            logger.error("确认档案调取失败", e);
            return Result.fail(500, "确认失败：" + e.getMessage());
        }
    }

    @Override
    public Result<String> confirmReturn(Integer requestId) {
        try {
            PhysicalArchiveRetrievalRequest request = requestMapper.selectById(requestId);
            if (request == null) {
                return Result.fail(404, "申请不存在");
            }

            if (!request.getIsRetrieved()) {
                return Result.fail(400, "档案未调取，无法归还");
            }

            if (request.getActualReturnTime() != null) {
                return Result.fail(400, "档案已归还");
            }

            // 更新归还时间
            request.setActualReturnTime(new Date());

            int result = requestMapper.updateById(request);
            
            if (result > 0) {
                // 记录系统日志
                systemLogService.recordLog(request.getUserId(), "确认纸质档案归还", 
                    "申请ID: " + requestId + ", 归还时间: " + new Date());
                
                return Result.success("档案归还确认成功");
            } else {
                return Result.fail(500, "确认失败");
            }
        } catch (Exception e) {
            logger.error("确认档案归还失败", e);
            return Result.fail(500, "确认失败：" + e.getMessage());
        }
    }

    /**
     * 生成调取码
     */
    private String generateRetrievalCode() {
        return "RET" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6).toUpperCase();
    }
} 